import {Component} from '@angular/core';
import {ArticleService} from '../../../service/article.service';
import {ArticleModel} from '../../../models/article.model';
import {ToasterService, ToasterConfig, Toast, BodyOutputType} from 'angular2-toaster';
import 'style-loader!angular2-toaster/toaster.css';
import {ShareService} from '../../../service/share.service';

@Component({
  selector: 'ngx-tiny-mce-page',
  template: `
    <toaster-container [toasterconfig]="config"></toaster-container>
    <div class="row" style="margin-bottom: 12px;">
      <div class="col-1">
        <button class="btn btn-hero-primary" (click)="saveClick()">Save</button>
      </div>
      <div class="col-1">
        <button class="btn btn-hero-secondary">Cancel</button>
      </div>
    </div>
    <nb-card>
      <nb-card-header>
        <div>
          <input type="text" placeholder="Input the article title" class="form-control"
                 [(ngModel)]="article.articleTitle"/>
        </div>
      </nb-card-header>
      <nb-card-body>
        <ngx-tiny-mce (editorKeyup)="artcileDataEvent($event)"></ngx-tiny-mce>
      </nb-card-body>
    </nb-card>
  `,
})
export class TinyMCEComponent {

  article: ArticleModel;
  config: ToasterConfig = new ToasterConfig({
    positionClass: 'toast-top-right',
    timeout: 5000,
    newestOnTop: true,
    tapToDismiss: true,
    preventDuplicates: false,
    animation: 'fade',
    limit: 5,
  });

  constructor(private articleService: ArticleService, private toasterService: ToasterService,
              private shareService: ShareService) {
    this.article = new ArticleModel();
    this.shareService.getData().subscribe(res => {
      this.article.userId = res.id;
    });

  }



  saveClick(): void {
    // value check
    if (this.article.articleTitle === undefined ||
      this.article.articleTitle === null ||
      this.article.articleTitle === '') {

      const toast: Toast = {
        type: 'warning',
        title: 'Article Title',
        body: 'Please input article',
        showCloseButton: true,
        bodyOutputType: BodyOutputType.TrustedHtml,
      };
      this.toasterService.popAsync(toast);
      return;
    }

    this.articleService.saveArticle(this.article).subscribe(data => {
      this.article = data;

      this.toasterService.popAsync('success', 'update', 'Update Success');
    })
  }

  artcileDataEvent(event) {
    this.article.content = event;
  }
}
